package com.zhh.srforum.advice;

import com.alibaba.fastjson.JSON;
import com.zhh.srforum.dto.ResultDTO;
import com.zhh.srforum.exception.CustomizeErrorCode;
import com.zhh.srforum.exception.CustomizeException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Zhao Haihang
 * @Date: 2020/11/23/20:42
 * @Description:
 */
@ControllerAdvice
public class CustomizeExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handler(Throwable throwable, Model model,HttpServletRequest request, HttpServletResponse response){
       String contentType = request.getContentType();
       if("application/json".equals(contentType)){
           // 返回 JSON
           ResultDTO resultDTO;
           if (throwable instanceof CustomizeException) {
               resultDTO = ResultDTO.errorOf((CustomizeException) throwable);
           } else {
               resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
           }

           try {
               response.setContentType("application/json");
               response.setStatus(200);
               response.setCharacterEncoding("utf-8");
               PrintWriter writer = response.getWriter();
               writer.write(JSON.toJSONString(resultDTO));
               writer.close();
           } catch (IOException ioe) {
           }
           return null;
       }else{
           if (throwable instanceof CustomizeException) {
               model.addAttribute("message", throwable.getMessage());
           } else {
               model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
           }
           return new ModelAndView("error");
       }
    }
}
